<?php

namespace App\Console\Commands\Cruise;

use App\Library\Rms\RmsUserApi;
use App\Models\Common\FsCompanyModel;
use App\Models\Common\FsCompanyRoleMappingModel;
use App\Models\Cruise\CruiseCheckAgainstModel;
use App\Models\Cruise\CruiseCheckDetailModel;
use App\Models\Cruise\CruiseCheckRectifyModel;
use App\Models\Cruise\CruiseOrderModel;
use App\Models\Cruise\CruiseTemplateModel;
use App\Models\Kms\User\KmsUser;
use App\Models\Kms\User\User;
use App\Service\Cruise\Check\CruiseCheckAgainstService;
use App\Service\Cruise\Check\CruiseCheckSmsService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Overtrue\EasySms\Exceptions\InvalidArgumentException;

class CruiseInspectionTaskSendSms extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cruise:inspectionTaskSendSms';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '巡检任务待审核（三方审核人员）-当有待初审任务时，每天三个时间点进行统一提醒。';

    /**
     * @throws InvalidArgumentException
     */
    public function handle()
    {
        // 门店稽核 && 待初审的任务
        $globalMsg = [];
        CruiseOrderModel::query()
                        ->with('checkTaskDetailRel')
                        ->where('type', CruiseTemplateModel::TYPE_3)
                        ->where('status', CruiseOrderModel::STATUS_WAIT_MODIFY_EXT)
                        ->chunkById(100, function ($item) use (&$globalMsg) {
                            foreach ($item as $cruiseOrderModel) {
                                if (!$cruiseOrderModel->checkTaskDetailRel) {
                                    return;
                                }
                                if ($cruiseOrderModel->checkTaskDetailRel->checkType != CruiseCheckDetailModel::CHECK_TYPE_THIRD_PARTY) {
                                    return;
                                }
                                // company
                                if (!$cruiseOrderModel->checkTaskDetailRel->companyId) {
                                    return;
                                }

                                $fsCompanyId = FsCompanyModel::query()->where('departmentId',
                                    $cruiseOrderModel->checkTaskDetailRel->companyId)->value('id');
                                // userIds
                                $userIds = FsCompanyRoleMappingModel::getCompanyUserIdsByRole($fsCompanyId,
                                    FsCompanyRoleMappingModel::ROLE_ID_COMPANY_FIRST);

                                $taskName = $cruiseOrderModel->checkTaskDetailRel->taskName;

                                foreach ($userIds as $userId) {
//                                    if (empty($globalMsg[$userId][$taskName])) {
//                                        $globalMsg[$userId][$taskName] = [
//                                            'num' => 0,
//                                        ];
//                                    }
//
//                                    $globalMsg[$userId][$taskName]['num']++;

                                    if (empty($globalMsg[$userId])) {
                                        $globalMsg[$userId] = [
                                            'num' => 0,
                                        ];
                                    }

                                    $globalMsg[$userId]['num']++;

                                }
                            }
                        });

        // 获取所有用户信息
        $userIds   = array_unique(array_keys($globalMsg));
        $allMobile = [];
        collect($userIds)->chunk(200)->each(function ($ids) use (&$allMobile) {
            $ids        = $ids->toArray();
            $searchList = collect((new RmsUserApi())->getUserInfoByIds($ids,
                ['id', 'username', 'mobile'])['data'] ?? [])
                ->map(function ($item) {
                    return [
                        'id'     => $item['id'],
                        'name'   => $item['username'],
                        'mobile' => $item['mobile']
                    ];
                })->toArray();

            $allMobile = array_merge($allMobile, $searchList ?? []);
        });

        $allMobile = array_column($allMobile, null, 'id');

        foreach ($globalMsg as $userId => $msgList) {
//            foreach ($msgList as $taskName => $taskInfo) {
            $mobile     = $allMobile[$userId]['mobile'];
            $num        = $msgList['num'];
            $taskStatus = '待初审';
            $taskName   = '';
//            dump($mobile . '-' . $num . ':' . $taskStatus);
//            循环发送短信
            CruiseCheckSmsService::sendInspectionTask($mobile, $num, $taskName, $taskStatus);
//            }
        }

    }
}
